package org.yan.kangaroo.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yan.kangaroo.common.response.BaseResponseCodeEnum;
import org.yan.kangaroo.common.response.Result;

/**
 * 全局异常处理
 *
 * @author wangx
 * @date 11/09/2019 9:28
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionController {


    @ExceptionHandler(value = KangarooBaseException.class)
    public Result<?> handlerMcpBaseException(KangarooBaseException e) {
        return Result.error(e.getResponseCode());
    }

    @ExceptionHandler(value = Exception.class)
    public Result<?> handlerException(Exception e) {
        log.error("[handlerException] error:", e);
        return Result.error(BaseResponseCodeEnum.ERROR);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Result<?> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("[handlerMethodArgumentNotValidException] error", e);
        return handlerParamsException(e.getBindingResult());
    }

    private Result<?> handlerParamsException(final BindingResult bindingResult) {
        StringBuilder message = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {
            message.append("[");
            message.append(error.getField()).append(":").append(error.getDefaultMessage());
            message.append("]");
            message.append(" ");
        }
        return Result.fail("400", message.toString());
    }
}
